<template>
  <div>
    <div>
      <div v-if="imgUrl" class="amap-img">
        <i class="el-icon-error icon-minus" @click.prevent="remove"></i>
        <div class="address">
          <div class="address-title">
            {{ building }}
            <el-tooltip class="item" effect="dark" content="复制地址" placement="top">
              <i class="el-icon-document-copy" style="color: #409EFF;" @click="copyAddress"></i>
            </el-tooltip>
          </div>
          <div class="address-text"> {{ address }}
            <div class="icon-location" @click.stop="openAmap">
              <el-tooltip class="item" effect="dark" content="重新定位" placement="top">
                <i class="el-icon-location-outline"></i>
              </el-tooltip>
            </div>
          </div>
        </div>
        <a :href="ahref" target="_blank">
          <el-image style="width: 350px; height: 110px" :src="imgUrl" fit="scale-down"></el-image>
        </a>
      </div>
      <el-button v-else type="primary" icon="el-icon-location-outline" @click="openAmap"></el-button>
    </div>

    <amapDialog @setLnglats="getLnglats" v-if="dialogVisible" :defaultLnglat="lnglat" :dialogVisible.sync="dialogVisible" @openAmapInit="getAmapInit">
    </amapDialog>
  </div>
</template>
<script>
import amapDialog from "./amap-dialog.vue"
import axios from "axios"
import AMapLoader from "@amap/amap-jsapi-loader"
import { localStore } from '@/utils/sessionStore'

const globalConfig = localStore.get('globalConfig') // 读取全局配置
export default {
  name: "amap",
  props: {
    value: {},
  },
  components: { amapDialog },

  data() {
    return {
      dialogVisible: false,
      lnglat: null,
      imgUrl: "",
      address:"",
      building:"",

    }
  },

  computed: {
    //申请的Web端(JS API) key
    key() {
      if (globalConfig && globalConfig.amap) {
        return globalConfig.amap.key
      }else{
        return ""
      }
    },
    //申请的Web端(JS API) security
    securityJsCode(){
      if (globalConfig && globalConfig.amap) {
        return globalConfig.amap.securityJsCode
      }else{
        return ""
      }
    },
    //申请的Web服务key
    webServerKey(){
      if (globalConfig && globalConfig.amap) {
        return globalConfig.amap.webServerKey
      }else{
        return ""
      }    
    },
    ahref() {
      if (this.lnglat) {
        const lng = this.lnglat.split(",")[0]
        const lat = this.lnglat.split(",")[1]
        return `https://ditu.amap.com/regeo?lng=${lng}&lat=${lat}&src=uriapi&innersrc=uriapi`
      } else {
        return ""
      }
    },
  },
  mounted() {
    console.log(this.value,'value---mounted')
    if(this.value){
      this.amapInit()
    }
  },
  watch: {
    lnglat: {
      immediate:true,
      deep: true,
      handler(val) {
        if (val) {
          this.regeoCode()
          this.getamapImg()
         
        }
      },
    },
  },
  methods: {
    openAmap() {
      this.dialogVisible = true
    },
    amapInit(){
    window._AMapSecurityConfig = {
      securityJsCode:this.securityJsCode,
    }
      setTimeout(()=>{
        AMapLoader.load({
        key: this.key, // 申请好的Web端开发者Key，首次调用 load 时必填
        plugins: [
          "AMap.AutoComplete",
          "AMap.PlaceSearch",
          "AMap.Marker",
          "AMap.InfoWindow",
          "AMap.Pixel",
          "AMap.Geocoder",
        ], // 需要使用的的插件列表
        version: "2.0",
      }).then((AMap) => {
        this.lnglat = this.value
      })
      },800)
    },
    getamapImg() {
      const url = `https://restapi.amap.com/v3/staticmap?location=${this.lnglat}&zoom=15&scale=2&size=350*110&markers=mid,,A:${this.lnglat}&key=${this.webServerKey}`
      try {
      axios.get(url, { responseType: "blob" }).then((res) => {
          console.log(res,'res--')
        this.imgUrl = window.URL.createObjectURL(res.data) // 获取对象url
        this.$emit("confirmAmap", {
            lnglat:this.lnglat,
            building:this.building,
            address:this.address,
            imgUrl:this.imgUrl
          })
      })
      } catch (error) {
        console.error(error,'获取地图图片失败')
      }

    },
    regeoCode() {
      const geocoder = new AMap.Geocoder({
        city: "010", //城市设为北京，默认：“全国”
        radius: 500, //范围，默认：500
      })
      const lnglats = this.lnglat.split(",")
      console.log(lnglats, "lnglats")
      geocoder.getAddress(lnglats, (status, result) => {
        try {
          console.log(status, result,'=====status, result')
          if (status === "complete" && result.regeocode) {
            this.address = result.regeocode.formattedAddress
            this.building = result.regeocode.addressComponent.building || "位置"
           
          } else {
            console.error("根据经纬度查询地址失败")
          }
        } catch (error) {
          console.error(error)
        }
      })
    },
    getLnglats(lnglat) {
      this.lnglat = lnglat
      this.$emit('input',lnglat)
    },
    	// 复制地址
    copyAddress() {
    let input = document.createElement("input"); // 创建input对象
     input.value = this.address; // 设置复制内容
     document.body.appendChild(input); // 添加临时实例
     input.select(); // 选择实例内容
     document.execCommand("Copy"); // 执行复制
     document.body.removeChild(input); // 删除临时实例
     this.$message.success('复制地址成功');
    },
    remove() {
      this.lnglat = null
      this.imgUrl = ""
    },
    getAmapInit({ amap, callback }){
      this.$emit("openAmapInit", {
                amap:amap,
                callback: (amap) => {
                  callback(amap)
          },
      })
    }
  },
}
</script>
<style lang="scss" scoped>
.amap-img {
  position: relative;
  width: 350px;
  height: 180px;
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 5px;

  .address {
    height: 70px;
    padding-left: 10px;

    .address-title {
      font-size: 14px;
      font-weight: 700;
    }

    .address-text {
      color: rgb(51, 51, 51);
      font-size: 12px;
      overflow: hidden;
      text-overflow: ellipsis;
      -o-text-overflow: ellipsis;
      white-space: nowrap;
      width: 100%;
      position: relative;

      .icon-location {
        position: absolute;
        right: 0;
        top: 0;
        font-size: 20px;
        color: #409EFF;
        background-color: #fff;
      }
    }
  }

  &:hover .icon-minus {
    display: block;
  }

  .icon-minus {
    position: absolute;
    display: none;
    right: 0;
    top: 0;
    z-index: 999;
  }
}

.amap-img:hover {
  box-shadow: 2px 5px 5px #888888;
}
</style>
